const { prisma } = require('../config/prisma');

/**
 * 获取积分记录列表
 */
const getPointsRecords = async (req, res) => {
  try {
    const { page = 1, size = 20 } = req.query;
    const skip = (page - 1) * size;

    const [total, records] = await Promise.all([
      prisma.pointsRecord.count({
        where: { userId: req.user.id }
      }),
      prisma.pointsRecord.findMany({
        where: { userId: req.user.id },
        orderBy: { createdAt: 'desc' },
        skip,
        take: parseInt(size),
        select: {
          id: true,
          points: true,
          type: true,
          remark: true,
          createdAt: true
        }
      })
    ]);

    res.json({
      code: 0,
      data: {
        total,
        list: records
      }
    });
  } catch (error) {
    console.error('Get points records error:', error);
    res.status(500).json({
      code: 500,
      message: '获取积分记录失败'
    });
  }
};

/**
 * 获取今日积分统计
 */
const getTodayPoints = async (req, res) => {
  try {
    // 获取积分配置
    const pointsConfig = await prisma.systemConfig.findUnique({
      where: { key: 'points_exercise' }
    });
    
    if (!pointsConfig) {
      throw new Error('Points configuration not found');
    }

    const { daily_limit } = JSON.parse(pointsConfig.value);

    // 获取今天的开始时间
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // 获取今日获得的积分总数
    const todayPoints = await prisma.pointsRecord.aggregate({
      where: {
        userId: req.user.id,
        type: 1, // 只统计获得的积分
        createdAt: {
          gte: today
        }
      },
      _sum: {
        points: true
      }
    });

    const todayEarned = todayPoints._sum.points || 0;
    const remainPoints = Math.max(0, daily_limit - todayEarned);

    res.json({
      code: 0,
      data: {
        today_points: todayEarned,
        remain_points: remainPoints
      }
    });
  } catch (error) {
    console.error('Get today points error:', error);
    if (error.message === 'Points configuration not found') {
      return res.status(500).json({
        code: 500,
        message: '系统配置错误'
      });
    }
    res.status(500).json({
      code: 500,
      message: '获取今日积分统计失败'
    });
  }
};

module.exports = {
  getPointsRecords,
  getTodayPoints
}; 